package me.zhengjie.modules.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.service.other.domain.*;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.property.domain.FirsthandEstate;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.PropertyService;
import com.qiaofang.common.request.DataRequest;
import com.qiaofang.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.service.constants.SyncConstants;
import me.zhengjie.modules.quartz.service.dto.SyncCommon;
import me.zhengjie.modules.sync.request.FirsthandRulesDTO;
import me.zhengjie.modules.sync.request.PropertyRulesDTO;
import me.zhengjie.modules.sync.request.SysFieldSyncRequest;
import me.zhengjie.modules.sync.request.UpDownProcessingRequest;
import me.zhengjie.modules.sync.response.SysFieldSyncResponse;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class PropertyRoleBrushTask {

    private static final String SYS_FIELD_SYNC_API = "/api/dataprocessing/syncData/sysFieldList";

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private MongoTemplate mongoTemplate;

    private RestTemplate template;

    {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000);
        requestFactory.setReadTimeout(30000);
        template = new RestTemplate(requestFactory);
    }


    public void run() {
        log.info("PropertyRoleBrushTask run start");
        Corporation corporation = new Corporation();
        corporation.setDeleted(Boolean.FALSE);
        corporation.setV20Flag(Boolean.FALSE);
        Iterable<Corporation> list = corporationService.findAll(Example.of(corporation));
        list.forEach(item -> {
            String corporationCode = item.getCorporationCode();
            //未配置上下架数据处理域名
            if (StringUtil.isEmpty(item.getPullDomain())) {
                log.error("集团:{} 的同步数据域名未配置", corporationCode);
                return;
            }

            Criteria criteria = Criteria.where("corporationCode").is(corporationCode).and("status").is(1);
            List<CityCompany> companies = mongoTemplate.find(new Query(criteria), CityCompany.class);
            companies.forEach(company -> {
                SyncCommon syncCommon = new SyncCommon();
                syncCommon.setCorporationCode(item.getCorporationCode());
                syncCommon.setAppId(item.getPullAppId());
                syncCommon.setAppKey(item.getPullAppKey());
                syncCommon.setDomain(item.getPullDomain());
                syncCommon.setCityCode(company.getCityCode());
                syncCommon.setCompanyUuid(company.getCompanyUuid());

                log.info("开始处理公司:{}的房源角色参数，开始时间:{}", company.getCompanyUuid(), new Date());
                updatePropertyRoles(syncCommon, company);
                log.info("完成处理公司:{}的房源角色参数，结束时间:{}", company.getCompanyUuid(), new Date());
            });
        });
        log.info("PropertyRoleBrushTask run end");
    }

    private void updatePropertyRoles(SyncCommon syncCommon, CityCompany cityCompany) {
        EmpShowRules propertyShowRules = cityCompany.getPropertyShowRules();
        List<PropertyRole> roleList = propertyShowRules.getRoleList();
        SysFieldSyncRequest sysFieldSyncRequest = new SysFieldSyncRequest();
        if (!CollectionUtils.isEmpty(roleList)){
            sysFieldSyncRequest.setTiming(getDayZero(DateUtils.addDays(new Date(), -1)));
        }
        SysFieldSyncResponse response = httpRequestData(sysFieldSyncRequest, syncCommon, SYS_FIELD_SYNC_API);
        if (response == null){
            return;
        }
        Integer opFlag = response.getOpFlag();
        List<PropertyRole> sysFieldList = response.getSysFieldList();
        if (opFlag == 4){
            return;
        }else if (opFlag == 1){
            //初始化
            propertyShowRules.setRoleList(sysFieldList);
        }else if (opFlag == 2){
            //刷新
            Map<Long, PropertyRole> roleMap = roleList.stream().collect(Collectors.toMap(PropertyRole::getRoleId, a -> a, (k1, k2) -> k1));
            if (roleList.size() > 3) {
                roleList = roleList.subList(0, 3);
            }
            for (PropertyRole propertyRole : sysFieldList) {
                if (roleMap.get(propertyRole.getRoleId()) != null){
                    PropertyRole oldPropertyRole = roleMap.get(propertyRole.getRoleId());
                    propertyRole.setSort(oldPropertyRole.getSort());
                    propertyRole.setShowOrHide(oldPropertyRole.isShowOrHide());
                    propertyRole.setFixedShow(oldPropertyRole.isFixedShow());
                }
            }
            roleList.addAll(sysFieldList);
            propertyShowRules.setRoleList(roleList);
        }else if (opFlag == 3){
            //删除
            propertyShowRules.setRoleList(roleList.size() > 3 ? roleList.subList(0, 3) : roleList);
        }
        cityCompany.setPropertyShowRules(propertyShowRules);
        cityCompany.setUpdateTime(new Date());
        cityCompanyService.save(cityCompany);
    }

    private HttpHeaders getHeaders(SyncCommon syncCommon) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("X-AUTH-APP-ID", syncCommon.getAppId());
        headers.add("X-AUTH-KEY", syncCommon.getAppKey());
        headers.add("companyUuid", syncCommon.getCompanyUuid());
        log.info("========>headers:{}", JSON.toJSONString(headers));
        return headers;
    }

    private SysFieldSyncResponse httpRequestData(SysFieldSyncRequest bodys, SyncCommon syncCommon, String apiUrl) {
        HttpHeaders headers = getHeaders(syncCommon);
        DataRequest dataRequest = new DataRequest();
        dataRequest.setParam(bodys);
        String url = syncCommon.getDomain() + apiUrl;
        String result = null;
        log.info("sync params {},header {}", dataRequest, headers);
        try {
            result = template.postForObject(url, new HttpEntity<>(dataRequest, headers), String.class);
            log.info("sync result {}", result);
        } catch (Exception e) {
            log.error("httpRequest error", e);
        }

        if (Objects.isNull(result)) {
            return null;
        }
        JSONObject resultObject = JSON.parseObject(result);
        if (null == resultObject) {
            return null;
        }
        String responseCode = resultObject.getString("responseCode");
        if (!SyncConstants.ON.equals(responseCode)) {
            String responseMessage = resultObject.getString("responseMessage");
            log.info("sync error {}", responseMessage);
            return null;
        }
        if (Objects.isNull(resultObject)) {
            return null;
        }
        JSONObject data = resultObject.getJSONObject("data");
        return data.toJavaObject(SysFieldSyncResponse.class);
    }

    private Date getDayZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
}
